#include <isr.h>
#include <io.h>
#include <defs.h>
#include <ts7200.h>
#include <timer.h>
#include <vic.h>
#include <uart.h>
#include <terminal.h>
#include <string.h>
#include <utils.h>
#include <bwio.h>

void DefaultHandler( sched *s, td *task ) {
  // We received an interrupt that our system doesn't handle; panic!
  SysPanic(s, task, "DefaultHandler", "Unknown interrupt occurred");
}

void TimerHandler( sched *s, td *task ) {
  timer *const timer3 = (timer*)( TIMER3_BASE );
  timer3->clear = 0;
  WakeAwaiters(s, task, EVENT_TIMER, SUCCESS, NULL, 0);
}

void Uart1Handler( sched *s, td *task ) {
  uart *const uart1 = (uart*)( UART1_BASE );
  int int_flags = uart1->intl_d_int_clr;

  if (int_flags & MIS_MASK) {
    uart1->intl_d_int_clr = 0;
    WakeAwaiters(s, task, EVENT_UART1_TX, int_flags, NULL, 0);
  } else {
    uart1->ctrl &= ~(RIEN_MASK | RTIEN_MASK);
    WakeAwaiters(s, task, EVENT_UART1_RX, int_flags, NULL, 0);
  }
}

void Uart2Handler( sched *s, td *task ) { 
  uart *const uart2 = (uart*)( UART2_BASE );
  int int_flags = uart2->intl_d_int_clr;

  if (int_flags & TIS_MASK) {
    uart2->ctrl &= ~(TIEN_MASK);
    WakeAwaiters(s, task, EVENT_UART2_TX, int_flags, NULL, 0);
  } else {
    uart2->ctrl &= ~(RIEN_MASK | RTIEN_MASK);
    WakeAwaiters(s, task, EVENT_UART2_RX, int_flags, NULL, 0);
  }
}
